/*
   @Copyright:LintCode
   @Author:   tjyemail
   @Problem:  http://www.lintcode.com/problem/insert-node-in-a-binary-search-tree
   @Language: C++
   @Datetime: 16-02-09 04:49
   */

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */

// Method 1, loop
class Solution {
public:
	/**
	 * @param root: The root of the binary search tree.
	 * @param node: insert this node into the binary search tree
	 * @return: The root of the new binary search tree.
	 */
	TreeNode* insertNode(TreeNode* root, TreeNode* node) {
		// write your code here
		for(TreeNode *p=root;p;){
			if (p->val>node->val){
				if (p->left==NULL){
					p->left= new TreeNode(node->val);
					return root;
				}
				p=p->left;
			}
			else if (p->val<node->val){
				if (p->right==NULL){
					p->right = new TreeNode(node->val);
					return root;
				}
				p=p->right;
			}
			else return root;
		}
		return new TreeNode(node->val);
	}
};

// Method 2, recursion
class Solution {
public:
	/*
	 * @param root: The root of the binary search tree.
	 * @param node: insert this node into the binary search tree
	 * @return: The root of the new binary search tree.
	 */
	TreeNode * insertNode(TreeNode * root, TreeNode * node) {
		// write your code here
		if(root==NULL) return node;
		if(root->val>node->val)
			root->left=insertNode(root->left,node);
		if(root->val<node->val)
			root->right=insertNode(root->right,node);
		return root;
	}
};
